package com.softtown.common.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.softtown.common.exception.ErrorCode;
import com.softtown.common.exception.RenException;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: Dingyayong
 * @Date: 2019/7/10 14:48
 * @Description:
 */
public class FileUploadUtil {
     static COSCredentials cosCredentials
            = new BasicCOSCredentials("AKIDJTLONFDFLTUKl4xwfEdrbAOcYJxfCjuK","1zn7GGAtxDNL0Unx1yd7VVM5iB3pPsEO");
     static ClientConfig clientConfig
            = new ClientConfig(new Region("ap-shanghai"));
     static COSClient cosClient
            = new COSClient(cosCredentials,clientConfig);
     static String bucketName = "soumousing-1259564964";
     static String qcloudDomain =	"https://soumousing-1259564964.file.myqcloud.com";

    public static String upload(InputStream inputStream, String key) {
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(inputStream.available());
            PutObjectRequest request = new PutObjectRequest(bucketName, key, inputStream, metadata);
            PutObjectResult result = cosClient.putObject(request);

            cosClient.shutdown();
            if(result.getETag() == null){
                throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, "");
            }
        } catch (IOException e) {
            throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }

        return  qcloudDomain + "/"+ key;
    }
    /**
     * 删除
     */
    public static void delete(String key) {
                // 指定要删除的 bucket 和路径
                try {
                    cosClient.deleteObject(bucketName , key);
                    System.out.println("删除成功");
                } catch (Throwable tb) {
                    System.out.println("删除文件失败");
                    tb.printStackTrace();
                }
    }
}
